import {getUserAbout} from "@/utils/userabout";
import {reqLogin, reqLogout, reqRegister, reqSendCode, reqUserInfo} from "@/api";

const state = {
    userTempId:getUserAbout(),
    token:localStorage.getItem('TOKEN_SKU'),
    userInfo:{}
}
const mutations = {
    RESEIVE_USERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    RECEIVE_TOKEN(state, token) {
        state.token = token;
    },
    RECEIVE_RESETTOKEN(state){
        state.token = ""
    }
}
const actions = {
    //退出登录
    async setLogout({commit,dispatch}){
      const result = await reqLogout();
      if (result && result.code === 200){
          dispatch('resetToken');
          commit('RESEIVE_USERINFO',{});
          return "成功";
      }else{
          return Promise.reject(new Error("退出登录失败"));
      }
    },
    //清除token获取新的token
    resetToken({commit}){
        localStorage.removeItem('TOKEN_SKU');
        commit('RECEIVE_RESETTOKEN');
    },
    //获取验证码
    async sendCode({commit},phone){
        // console.log(phone)
        const result = await reqSendCode(phone);
        if (result && result.code === 200){
            return result.data
        }else{
            return Promise.reject(new Error("请求验证码失败"));
        }
    },
    //注册
    async setRegister({commit},data){
        const result = await reqRegister(data);
        if (result && result.code === 200){
            return "成功"
        }else {
            return Promise.reject(new Error("注册失败"));
        }
    },
    //登录
    async setLogin({commit},data){
        const result = await reqLogin(data);
        if (result && result.code === 200){
            console.log(result)
            commit('RECEIVE_TOKEN',result.data.token);
            localStorage.setItem('TOKEN_SKU',result.data.token);
            return "成功"
        }else{
            return Promise.reject(new Error("登录失败，账号或者密码错误"));
        }
    },
    //获取用户信息
    async getUserInfo({commit}){
      const result =  await reqUserInfo();
      if (result && result.code === 200){
          commit('RESEIVE_USERINFO',result.data);
          return "成功"
      }else {
          return Promise.reject(new Error("获取用户信息失败"));
      }
    }
}
const getters = {}

export default {
    namespaced:true,
    state,
    mutations,
    actions,
    getters
}